package service

import (
	"git.oschina.net/fanbuchi/xgggh/oauth2/model"
	"git.oschina.net/fanbuchi/xgggh/oauth2/db"
)
//select client_id,expires_at,token,user_id   from oauth2.refresh_tokens;
//select client_id,expires_at,token,user_id   from oauth2.access_tokens;
func  GrantAccessToken(client *model.Client, account *model.Account, expiresIn int64, scope string) (*model.AccessToken, error) {
	// Begin a transaction
	tx := db.GetDB().Begin()

	// Delete expired access tokens
	query := tx.Unscoped().Where("client_id = ?", client.ID)
	if account != nil && account.ID > 0 {
		query = query.Where("account_id = ?", account.ID)
	} else {
		query = query.Where("account_id IS NULL")
	}

	if err := query/*.Where("expires_at <= ?", time.Now())*/.
		Delete(new(model.AccessToken)).Error; err != nil {
		tx.Rollback() // rollback the transaction
		return nil, err
	}

	// Create a new access token
	accessToken := model.NewAccessToken(client, account, expiresIn, scope)
	if err := tx.Create(accessToken).Error; err != nil {
		tx.Rollback() // rollback the transaction
		return nil, err
	}
	accessToken.Client = client
	accessToken.Account = account

	// Commit the transaction
	if err := tx.Commit().Error; err != nil {
		tx.Rollback() // rollback the transaction
		return nil, err
	}

	return accessToken, nil
}
